package com.etrans.web.gps.business.system.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.system.domain.AreaCheck;
import com.etrans.web.gps.business.system.domain.CheckResult;
import com.etrans.web.gps.business.system.domain.QueryAreaCheck;
import com.etrans.web.gps.business.system.domain.Strategy;
import com.etrans.web.gps.business.system.domain.SysUser;
import com.etrans.web.gps.business.system.service.AreaCheckService;
import com.etrans.web.gps.business.system.service.CommonService;
import com.etrans.web.gps.common.Constant;
import com.etrans.web.gps.common.page.PageResultVo;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.util.grid.FlexiGridUtil;
import com.etrans.web.gps.util.grid.ParamMap;
import com.etrans.web.gps.util.grid.ParamValueObject;

/**
 *	区域查岗
 * @author jw.chen
 *
 */
@Controller
@RequestMapping("/system/areaCheck/*")
public class AreaCheckController extends BaseController {
	

	private static final Logger logger = LoggerFactory.getLogger(AreaCheckController.class);

	
	@Autowired
	private AreaCheckService areaCheckService;
	
	@Autowired
	private CommonService commonService;
	
	
	
	/**
	 * 跳转区域查岗记录列表界面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "toAreaCheck.html")
	public ModelAndView toAreaCheck(HttpServletRequest request, Model model) {
		ModelAndView mnv = new ModelAndView();
		mnv.setViewName("views/business/system/areaCheck/queryAreaCheck");
		return mnv;
	}
	
	/**
	 * 跳转区域查岗策略设置新增界面
	 * @return
	 */
	@RequestMapping(value = "initStrategys.html")
	public ModelAndView initStrategys() {
		ModelAndView mav = new ModelAndView();
		SysUser user = (SysUser)getSession().getAttribute(Constant.LOGIN_SESSION_NAME);
		// 根据当前登录用的对应的区域id查询区域Level
		Integer level = commonService.findAreaLevelById( user.getArea_id());
		if(level!=null){
			mav.getModel().put("level", level);
		}else{
			logger.error("获取当前登录人区域id对应的Level 失败");
		}
		mav.setViewName("views/business/system/areaCheck/addAreaStrategyForm");
		return mav;
	}
	
	
	/**
	 * 跳转区域用户查岗记录修改界面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "toUpdateAreaCheck.html")
	@ResponseBody
	public JSONObject toUpdateAreaCheck(HttpServletRequest request,HttpServletResponse response, String id) {
		JSONObject json = new JSONObject();
		try {
			List<QueryAreaCheck> list = areaCheckService.queryAreaCheckById(id);
			if(list != null && list.size() > 0){
				for (QueryAreaCheck queryAreaCheck : list) {
					json.put("data", queryAreaCheck);
				}
			}else{
				logger.error("根据id获取区域查岗记录多条、脏数据");
			}
		} catch (Exception e) {
			logger.error("获取区域查岗记录失败", e);
		}
		return json;
	}
	
	
	/**
	 * 当前区域用户查岗记录列表
	 * @param paramsGrid
	 * @return
	 */
	@RequestMapping(value="findAreaCheck.html")
	@ResponseBody
	public PageVo findAreaCheck(@RequestParam String paramsGrid){
		
		PageVo page = new PageVo();
		ParamMap param = FlexiGridUtil.parseJSONParam(paramsGrid);
		ParamValueObject inputParam = this.parseJSONParam(param);
		HashMap<String, Object> params=inputParam.getMapParams();
		// 获取当前登录对象
		SysUser user = (SysUser)getSession().getAttribute(Constant.LOGIN_SESSION_NAME);
		params.put("area_id", user.getArea_id());
		List<QueryAreaCheck> list = new ArrayList<>();
		try {	
			// 暂时先这么做，查询不在15分钟之内的、查岗结果是未应答的数据改成超时 [updateAreaCheckByCheckTime这里的代码提取到gps-task 项目里面去了]
//			areaCheckService.updateAreaCheckByCheckTime(params);
			// 查询结果
			list = areaCheckService.findAreaCheck(params);
			
			page.setRows(list);
			page.setPage((int) params.get("page"));
			page.setTotal(areaCheckService.findAreaCheckCount(params));
			
		} catch (Exception e) {
			logger.error("加载用户失败", e);
			e.printStackTrace();
		}
		return page;
	}
	
	/**
	 * top.jsp 定时检查是否有区域查岗信息
	 * @return
	 */
	@RequestMapping(value="taskAreaCheck.html")
	@ResponseBody
	public JSONObject taskAreaCheck(){
		JSONObject json = new JSONObject();
		HashMap<String, Object> params= new HashMap<>();
		// 获取当前登录对象
		SysUser user = (SysUser)getSession().getAttribute(Constant.LOGIN_SESSION_NAME);
		params.put("area_id", user.getArea_id());
		try {	
			long count = areaCheckService.taskAreaCheck(params);
			if(count != 0 ){
				json.put("flag", "1");
			}else{
				json.put("flag", "0");
			}
		} catch (Exception e) {
			logger.error("定时检查是否有区域查岗信息失败", e);
			e.printStackTrace();
		}
		return json;
	}
	
	
	/**
	 * 区域查岗应答修改
	 * @param request
	 * @param response
	 * @param queryAreaCheck
	 */
	@RequestMapping(value = "updateAreaCheck.html")
	@ResponseBody
	public void updateAreaCheck(HttpServletRequest request, HttpServletResponse response,
			QueryAreaCheck queryAreaCheck,String _id,String check_time1) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		PageResultVo pr = new PageResultVo();
		try {
			Date check_time = format.parse(check_time1);
			//说明： 查岗结果 1:正确 2:错误 3:超时 4:未应答
			queryAreaCheck.set_id(_id);
			queryAreaCheck.setCheck_time(check_time);
			if(queryAreaCheck.getReply_content().trim().equals(queryAreaCheck.getAnswer().trim())){
				queryAreaCheck.setCheck_result(CheckResult.CHECK_RESULT_1);
			}else{
				queryAreaCheck.setCheck_result(CheckResult.CHECK_RESULT_2);
			}
			areaCheckService.updateAreaCheck(queryAreaCheck);
			pr.setCode(Constant.RETURN_OK_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			pr.setCode(Constant.RETURN_ERROR_CODE);
			pr.setMsg("保存失败!");
		}
		ajaxResultJson(response, pr);
	}
	
	/**
	 * 区域查岗记录查询
	 * @param paramsGrid 
	 */
	@RequestMapping(value="loadAllAreaChecks.html")
	@ResponseBody
	public PageVo queryAreaCheckList(@RequestParam String paramsGrid){
		logger.info("{}{}:::::::查询区域查岗记录方法进入::::::::{}{}");
		PageVo page = new PageVo();
		Map<String, Object> paramMap = FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
		
		List<QueryAreaCheck> list = new ArrayList<>();
		try {	
			
			// 添加数据权限 ->当前登录用户对应的所有业户id
			SysUser user=getSysUser();
			paramMap.put("FullID", String.format("%08d", user.getArea_id()));
			// 添加数据权限
			
			// 查询结果
			list = areaCheckService.queryAreaCheckList(paramMap);
			
			logger.info("{}{}:::::::查询区域查岗记录条数::::::::{}{}", list.size());
			page.setRows(list);
			page.setPage((int) paramMap.get("page"));
			page.setTotal(areaCheckService.queryAreaCheckListCount(paramMap));
			
		} catch (Exception e) {
			logger.error("加载用户失败", e);
			e.printStackTrace();
		}
		return page;
	}
	/**
	 * 区域策略设置记录查询
	 * @param paramsGrid
	 * @return
	 */
	@RequestMapping(value="loadAllStrategys.html")
	public void queryAreaAllStrategys(HttpServletResponse response,HttpServletRequest request,@RequestParam String paramsGrid){
		
		Map<String, Object> params = FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
		// 添加数据权限 ->当前登录用户对应的所有业户id
		HashMap<String, Object> param = new HashMap<>();
		SysUser user = getSysUser();
		param.put("FullID", String.format("%08d", user.getArea_id()));
		List<HashMap<String, Object>> queryAreaTree = commonService.queryAreaTree(param);
		String checkTargetId = "";
		if (queryAreaTree != null && queryAreaTree.size() > 0) {
			for (HashMap<String, Object> hashMap : queryAreaTree) {
				// 所有的区域id
				checkTargetId = checkTargetId + hashMap.get("ID").toString()+",";
			}
			params.put("checkTargetId", checkTargetId.substring(0,checkTargetId.length()-1));
		} else {
			logger.info("当前登录人查询区域查岗记录操作---->数据权限---->当前登录人没有区域对应的区域id step1");
		}
		
		// 添加数据权限
		try {
			List<Strategy> rows = areaCheckService.queryAreaAllStrategys(params);
			Long total = areaCheckService.areaAllStrategysCount(params);
			PageVo pageBean = new PageVo();
			pageBean.setRows(rows);
			pageBean.setPage((int) params.get("page"));
			pageBean.setTotal(total.intValue());
			ajaxResultJson(response,pageBean);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 区域查岗策略设置记录删除
	 * @param response
	 * @param questionIds
	 */
	@RequestMapping(value="deleteStrategy.html")
	public void deleteStrategy(HttpServletResponse response,String strategyIds){
		PageResultVo pr = new PageResultVo();
		try {
			strategyIds=strategyIds.replaceAll("row", "");
			if(strategyIds != null && !"".equals(strategyIds)){
				String[] strategyId = strategyIds.split(",");
				for (String s : strategyId) {
					areaCheckService.deleteStrategy(Integer.parseInt(s));
				}
			}
			pr.setCode(Constant.RETURN_OK_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			pr.setCode(Constant.RETURN_ERROR_CODE);
			pr.setMsg("删除失败!");
		}
		
		ajaxResultJson(response, pr);
	}
	
	

	/**
	 * 区域查岗策略设置记录保存
	 * @param request
	 * @param response
	 * @param strategy
	 */
	@RequestMapping(value = "saveStrategy.html")
	public void saveStrategy(HttpServletRequest request, HttpServletResponse response,String selectType, String checkTime,
			String questionId,String question, String checkMode, String checkTargetIds,String  str,String answer ) {
		SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		PageResultVo pr = new PageResultVo();
		try {
			// 获取当前登录对象
			SysUser user = (SysUser)getSession().getAttribute(Constant.LOGIN_SESSION_NAME);
			
			
			if(checkTargetIds.length() > 0){
				
				String [] ids = checkTargetIds.substring(1, checkTargetIds.length()-1).replace("\"", "").split(",");
				String areaIds="";
				List<HashMap<String, Object>> listAreaIds = new ArrayList<>();
				HashMap<String, Object> params = new HashMap<>();
				// 省 selectType=1
				if(selectType.equals("1")){
					for (String id : ids) {
						areaIds = id;
					}
					params.put("level", selectType);
					params.put("areaIds", areaIds);
					// 保留 selectType = 1 的区域id
					listAreaIds = commonService.findAreaIdByLevelAndIds(params);
				}
				// 市  selectType=2
				else if(selectType.equals("2")){
					for (String id : ids) {
						areaIds = areaIds + id + ",";
					}
					params.put("level", selectType);
					params.put("areaIds", areaIds.substring(0, areaIds.length()-1));
					// 去掉区域表level = 1的区域id
					listAreaIds = commonService.findAreaIdByLevelAndIds(params);
					
				}
				// 区  selectType=3
				else{
					for (String id : ids) {
						areaIds = areaIds + id + ",";
					}
					params.put("level", selectType);
					params.put("areaIds", areaIds.substring(0, areaIds.length()-1));
					// 去掉区域表level = 2的区域id
					listAreaIds = commonService.findAreaIdByLevelAndIds(params);
				}
				
				// 自动-> 插入策略设置表->定时任务循环策略表->发指令->插入MONGODB区域查岗记录表
				if(checkMode.equals("1")){
					for (HashMap<String, Object> hashMap : listAreaIds) {
						
						Strategy strategy = new Strategy();
						// 查岗类型： 1：业户 2：区域（即管理机构） 
						strategy.setCheckType(2);
						// 查岗对象  如果 查岗类型是业户时，此处是业户的ID、查岗类型是区域时，此处是区域的ID,
						strategy.setCheckTargetId(Integer.valueOf(hashMap.get("ID").toString())); 
						// 题库id
						strategy.setQuestionId(Integer.valueOf(questionId));
						// 查岗时间->系统年 月 日+界面的 时 分 秒
						strategy.setCheckTime(format1.format(new Date())+" "+checkTime);
						// 查岗人
						String userName = user.getUser_name();
						strategy.setUserName(userName);
						// 保存方法调用
						areaCheckService.saveStrategy(strategy);
					}
				}
				
				// 手动-> 直接插入MONGODB区域查岗记录表
				if(checkMode.equals("2")){
				
					for (HashMap<String, Object> hashMap : listAreaIds) {
						
						// 查岗id
						int check_id = ThreadLocalRandom.current().nextInt();
						int check_type = 1; // 查岗方式  1:手动  2:自动
						String check_area_id = hashMap.get("ID")+"";
						
						
						String checkAreaName = hashMap.get("name")+"";
						
						// MONGODB _id= objectType:ObjectId:InfoId
						if(StringUtils.isNotBlank(check_area_id)){
							AreaCheck areaCheck = new AreaCheck();
							areaCheck.set_id(check_type+":"+check_area_id+":"+check_id);	// _id: "<check_type:check_area_id:check_id>",
							areaCheck.setCheck_time(new Date());							// 查岗时间
							areaCheck.setCheck_area_id(Integer.valueOf(check_area_id));		// 查岗区域ID
							areaCheck.setCheck_area_name(checkAreaName);					// 查岗区域名称
							areaCheck.setCheck_content(question);							// 查岗内容
							areaCheck.setChecker(user.getUser_name()); 						// 查岗人	(当前登录人)						
							areaCheck.setAnswer(answer);									// 答案
							areaCheck.setCheck_id(check_id);								// 查岗ID(暂时随机数)
							areaCheck.setCheck_type(1); 									// 查岗方式  1:手动  2:自动
							areaCheck.setCheck_result(4);									// 查岗结果 1:正确 2:错误 3:超时 4:未应答  (默认4:未应答)
							// 保存MONGODB
							areaCheckService.insertAreaCheckToMongodb(areaCheck);
						}else{
							logger.info("=========>区域手动查岗插入mongodb=======>区域id为空==========>");
						}
					}
					
				}
				
				
			}else{
				logger.info("=========>区域手动查岗插入mongodb=======>区域id为空==========>");
			}
			
			
			pr.setCode(Constant.RETURN_OK_CODE);
		} catch (Exception e) {
			e.printStackTrace();
			pr.setCode(Constant.RETURN_ERROR_CODE);
			pr.setMsg("保存失败!");
		}
		ajaxResultJson(response, pr);
	}

	
	/**
	 * 区域查岗记录导出
	 * @param request
	 * @param response
	 * @param queryParams
	 * @param title
	 * @param StartPage
	 * @param EndPage
	 * @param PageSize
	 * @param sortorder
	 * @param colModel
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "exportAreaChecks.html")
	public void exportAreaChecks( HttpServletRequest request, HttpServletResponse response, String queryParams, 
			String title, String StartPage, String EndPage, String PageSize,String colModel,String sortorder) {
		
		//获取参数
		HashMap<String, Object> params = new HashMap<String, Object>();
		List<String> colModelList = JSON.parseObject(colModel, List.class);
		try {
			Map<String, Object> paramMap = getReqParameters();
			List<String> whereParamsList = JSON.parseObject(paramMap.get("queryParams").toString(), List.class);
			for (Object object : whereParamsList) {
				JSONObject jsonObject = (JSONObject) object;
				params.put(jsonObject.get("name").toString(), jsonObject.get("value"));
			}
			// 分页条件
			int startPage = Integer.parseInt(StartPage);
			int endPage   = Integer.parseInt(EndPage);
			int pageSize  = Integer.parseInt(PageSize);
			params.put("page", startPage);
			params.put("pageSize", (endPage - startPage + 1) * pageSize);
			params.put("sortorder", sortorder); // 排序方式
			
			//传入条件从MongoDB中查询出数据
			List<QueryAreaCheck> list = areaCheckService.queryAreaCheckList(params);	
			List<HashMap<String, Object>> rows = new ArrayList<HashMap<String, Object>>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			for (QueryAreaCheck queryAreaCheck : list) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("check_area_name", queryAreaCheck.getCheck_area_name() == null ? "" : queryAreaCheck.getCheck_area_name().toString());
				map.put("check_time", 	   sdf.format(queryAreaCheck.getCheck_time()));
				map.put("check_content",   queryAreaCheck.getCheck_content() == null ? "" : queryAreaCheck.getCheck_content().toString());
				map.put("answer", 		   queryAreaCheck.getAnswer() == null ? "" : queryAreaCheck.getAnswer().toString());
				Date replyTime = queryAreaCheck.getReply_time();
				if(replyTime!=null){
					map.put("reply_time",   sdf.format(queryAreaCheck.getReply_time()));
				}else{
					map.put("reply_time",    "");
				}
				map.put("reply_content",   queryAreaCheck.getReply_content() == null ? "" : queryAreaCheck.getReply_content().toString());
				map.put("check_type", 	   queryAreaCheck.getCheck_type()== 1 ? "手动" : "自动");
				map.put("check_result",    getCheckResult(queryAreaCheck.getCheck_result()));
				rows.add(map);
			}
			int index = -1;
			List rowsList = new ArrayList<>();
			rowsList.add(rows);
			exportExl(request, response, title, removeHeadName(colModelList, index, -1), rowsList, null);
			
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("业户查岗导出败",e);
			
		}		
		
	}
	/**
	 * 转换名称
	 * @param check_result
	 * @return
	 */
	public String getCheckResult(int check_result){
		
		if(check_result == 1){
			return "正确";
		}
		else if(check_result == 2){
			return "错误";
		}
		else if(check_result == 3){
			return "超时";
		}
		else{
			return "未应答";
		}
	}
	
}
